<template>
  <a-card :bordered="false" class="card-area">
    <div :class="advanced ? 'search' : null">
      <!-- 搜索区域 -->
      <a-form layout="horizontal" :form="form">
        <div :class="advanced ? null: 'fold'">
          <a-row>
            <a-col :md="12" :sm="24">
              <a-form-item
                label="法人行"
                :labelCol="{span: 5}"
                :wrapperCol="{span: 16, offset: 1}">
                <a-select v-if="this.user.admin"
                          mode="default"
                          :allowClear="true"
                          style="width: 100%"
                          @change="handleInstChange"
                          v-model="query.instId">
                  <a-select-option v-for="r in instIdData" :key="r.label">{{r.label}}-{{r.value}}</a-select-option>
                </a-select>
                <a-input v-if="!this.user.admin" v-model="query.instId" :value="this.user.instId"
                         readonly="readonly"/>
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24" v-show="query.instId!=''">
              <a-form-item
                label="收单机构"
                :labelCol="{span: 5}"
                :wrapperCol="{span: 16, offset: 1}">
                <pagination-search-select v-model="query.acqInstCode" :listUrl="listUrl[1]" :listUrlParam="listUrlParam"
                                          valueName="id" :showNameArr="showNameArr"
                                          :pageSize="10" :openSearch="true" :searchWordKeyArr="orgCodeKey"
                                          ref="acqInstCodeSelect">
                </pagination-search-select>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :md="12" :sm="24" v-show="query.instId!=''">
              <a-form-item
                label="商户名称"
                :labelCol="{span: 5}"
                :wrapperCol="{span: 16, offset: 1}">
                <pagination-search-select v-model="query.mchntName" :listUrl="listUrl[0]" :listUrlParam="listUrlParam"
                                          valueName="id" :showNameArr="showNameArr"
                                          :pageSize="10" :openSearch="true" :searchWordKeyArr="signInstIdSearchKey"
                                          ref="mchntBaseInfoListByNameSelect">
                </pagination-search-select>
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24" v-show="query.instId!=''">
              <a-form-item
                label="二级商户"
                :labelCol="{span: 5}"
                :wrapperCol="{span: 16, offset: 1}">
                <a-select
                  mode="default"
                  :allowClear="true"
                  style="width: 100%"
                  show-search
                  placeholder="请选择二级商户"
                  :filter-option="filterOption"
                  option-filter-prop="children"
                  @focus="selectMchntNo"
                  @search="setMchntNoValue"
                  @select="setMchntNoValue"
                  v-model="query.mchntNo">
                  <a-select-option v-for="(d,index) in mchntNoList" :key="index">
                    {{ d.id}}-{{d.name}}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :md="12" :sm="24" v-show="query.instId!=''">
              <a-form-item
                label="交易类型"
                :labelCol="{span: 5}"
                :wrapperCol="{span: 16, offset: 1}">
                <a-select
                  mode="default"
                  :allowClear="true"
                  style="width: 100%"
                  show-search
                  placeholder="请选择交易类型"
                  :filter-option="filterOption"
                  option-filter-prop="children"
                  @focus="selectTxnName"
                  @search="selectTxnName"
                  @select="setTxnNameValue"
                  v-model="query.txnName">
                  <a-select-option v-for="(d,index) in txnNameList" :key="index">
                    {{ d.id}}-{{d.name}}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24" v-show="query.instId!=''">
              <a-form-item
                label="交易状态"
                :labelCol="{span: 5}"
                :wrapperCol="{span: 16, offset: 1}">
                <a-select
                  mode="default"
                  :allowClear="true"
                  style="width: 100%"
                  show-search
                  placeholder="请选择交易状态"
                  :filter-option="filterOption"
                  option-filter-prop="children"
                  @focus="selectTxnStatus"
                  @search="selectTxnStatus"
                  @select="setTxnStatusValue"
                  v-model="query.txnStatus">
                  <a-select-option v-for="(d,index) in txnStatusList" :key="index">
                    {{ d.id}}-{{d.name}}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :md="12" :sm="24" v-show="query.instId!=''">
              <a-form-item
                label="付款方账号"
                :labelCol="{span: 5}"
                :wrapperCol="{span: 16, offset: 1}">
                <a-input v-model="query.payerAcctInfo"/>
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24" v-show="query.instId!=''">
              <a-form-item
                label="商户订单号"
                :labelCol="{span: 5}"
                :wrapperCol="{span: 16, offset: 1}">
                <a-input v-model="query.mchntOrderId"/>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :md="12" :sm="24" v-show="query.instId!=''">
              <a-form-item
                label="最小交易金额"
                :labelCol="{span: 5}"
                :wrapperCol="{span: 16, offset: 1}">
                <a-input v-model="query.orderAmtStart"/>
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24" v-show="query.instId!=''">
              <a-form-item
                label="最大交易金额"
                :labelCol="{span: 5}"
                :wrapperCol="{span: 16, offset: 1}">
                <a-input v-model="query.orderAmtEnd"/>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :md="12" :sm="24" v-show="query.instId!=''">
              <a-form-item label="选择时间"
                           :labelCol="{span: 5}"
                           :wrapperCol="{span: 16, offset: 1}">
                <a-range-picker v-decorator="['timeForm']" format="YYYY-MM-DD" />
              </a-form-item>
            </a-col>

            <a-col :md="12" :sm="24" v-show="query.instId!=''">
              <a-form-item
                label="收银员"
                :labelCol="{span: 5}"
                :wrapperCol="{span: 16, offset: 1}">
                <a-select
                  mode="default"
                  :allowClear="true"
                  style="width: 100%"
                  show-search
                  placeholder="收银员"
                  :filter-option="filterOption"
                  option-filter-prop="children"
                  @focus="selectSyy"
                  @search="selectSyy"
                  @select="setSyyValue"
                  v-model="query.syy">
                  <a-select-option v-for="(d,index) in syyList" :key="index">
                    {{d.name}}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
        </div>
        <div v-show="query.instId!=''" style="margin-left: 38%">
          <a-button type="primary" @click="search">查询</a-button>
          <a-button style="margin-left: 8px" @click="reset">重置</a-button>
        </div>
      </a-form>
    </div>
    <div v-show="query.instId!=''">
      <div class="operator">
        <!--<a-button type="primary" @click="add">新增</a-button>-->
      </div>
      <!-- 表格区域 -->
      <a-table ref="table"
               :columns="columns"
               :rowKey="record => record.mchntOrderId"
               :dataSource="dataSource"
               :pagination="pagination"
               :loading="loading"
               :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
               :scroll="{ x: 2200 }"
               @change="handleTableChange">
        <template slot="email" slot-scope="text, record">
          <a-popover placement="topLeft">
            <template slot="content">
              <div>{{text}}</div>
            </template>
            <p style="width: 90px;margin-bottom: 0">{{text}}</p>
          </a-popover>
        </template>

      </a-table>

    </div>
  </a-card>
</template>
<script>
import moment from "moment";
import {mapState} from "vuex"
import ARow from "ant-design-vue/es/grid/Row";
import ACol from "ant-design-vue/es/grid/Col";
//下拉框分页
import PaginationSearchSelect from '@/components/select/PaginationSearchSelect'
moment.locale('zh-cn');

export default {
  name: "MchntOrderReport",
  components: {ACol, ARow,PaginationSearchSelect},
  data: function () {
    return {
      //下拉框 分页
      showNameArr:['id','name'],
      listUrl: ['/admin/igas/mchntOrderReport/mchntBaseInfoListByName','/admin/merParam/UpmpOrganization/instIdOrganizationSelect2List'],
      listUrlParam: {'instId': ''},
      signInstIdSearchKey:['mchntNo'],
      orgCodeKey:['orgCode'],
      //end
      advanced: false,
      form: this.$form.createForm(this),
      instIdData: [],
      timeForm: [],
      query: {
        instId: "",
        acqInstCode: "",
        mchntName: "",
        mchntNo: "",
        txnName: "",
        txnStatus: "",
        syy: "",
        frontSeqNum: "",
        payerAcctInfo: "",
        orderAmtStart: "",
        orderAmtEnd: "",
        mchntOrderId: "",
        startTime: "",
        endTime: "",
        hisTory: true
      },
      syyAboutId: '',
      selectedRowKeys: [],
      acqInstCodeList: [],
      mchntNameList: [],
      mchntNoList: [],
      txnNameList: [],
      txnStatusList: [],
      syyList: [],
      beanInfo: {},
      modalVisible: false,
      modalTitle: "",
      operationType: "add",
      loading: false,
      open: false,
      pagination: {
        pageSizeOptions: ["10", "20", "30", "40", "100"],
        defaultCurrent: 1,
        defaultPageSize: 10,
        showQuickJumper: true,
        showSizeChanger: true,
        showTotal: (total, range) =>
          `显示 ${range[0]} ~ ${range[1]} 条记录，共 ${total} 条记录`,
      },
      columns: [
        {
          title: "银行代码",
          dataIndex: "instId",
          width: 150,
          // fixed: 'left'
        },
        {
          title: "交易时间",
          dataIndex: "txnTime",
          width: 150,
        },
        {
          title: "请求流水号",
          dataIndex: "frontSeqNum",
          width: 150,
        },
        {
          title: "收单机构",
          dataIndex: "acqInstCode",
          width: 150,
        },
        {
          title: "商户名称",
          dataIndex: "mchntName",
          width: 200,
        },
        {
          title: "商户号",
          dataIndex: "mchntNo",
          width: 200,
        },
        {
          title: "终端编号",
          dataIndex: "termNo",
          width: 150,
        },
        {
          title: "商户订单号",
          dataIndex: "mchntOrderId",
          width: 150,
        },
        {
          title: "客户经理工号",
          dataIndex: "managerId",
          width: 150,
        },
        {
          title: "客户经理姓名",
          dataIndex: "managerName",
          width: 150,
        },
        {
          title: "付款方账号",
          dataIndex: "payerAcctInfo",
          width: 150,
        },
        {
          title: "发卡行",
          dataIndex: "issInstName",
          width: 150,
        },
        {
          title: "交易金额",
          dataIndex: "orderAmt",
          width: 150,
        },
        {
          title: "交易类型",
          dataIndex: "txnName",
          width: 150,
        },
        {
          title: "交易状态",
          dataIndex: "payBizStatus",
          width: 150,
          customRender: (text) => {
            return text ? {
              "00": '业务处理成功',
              "01": '业务处理中',
              "02": '业务处理失败',
              "03": '付款中',
              "10": '已撤销',
              "11": '已部分撤销',
              "20": '已冲正',
              "21": '已部分冲正',
              "30": '已全额退货',
              "31": '已部分退货',
              "32": '未确认收货全额退货',
              "33": '未确认收货部分退货',
              "40": '授权未完成',
              "41": '授权已完成',
              "50": '已确认收货',
              "51": '卡券已核销',
              "60": '已退汇',
              "99": '已清算',
            }[text] : ""
          }
        },
        {
          title: "相应信息描述",
          dataIndex: "orderDesc",
          width: 150,
        },
        {
          title: "撤销标志描述",
          dataIndex: "payerAcctType",
          width: 150,
          customRender: (text) => {
            return text ? {
              "10": '业务已撤销'
            }[text] : ""
          }
        },
        // {
        //   title: "退货标志",
        //   dataIndex: "bizStatus",
        //   width: 150,
        //   customRender: (text) => {
        //     return text ? {
        //       "30": '业务已退货',
        //       "31": '业务已退货'
        //     }[text] : ""
        //   }
        // },
        {
          title: "收银员",
          dataIndex: "userName",
          width: 150,
        },
        {
          title: "累计退货金额",
          dataIndex: "refundAmt",
          width: 150,
        },
        {
          title: "优惠金额",
          dataIndex: "orderDiscountAmt",
          width: 150,
        },
        // {
        //   title: "操作",
        //   fixed: "right",
        //   scopedSlots: {customRender: "operation"},
        // },
      ],
      dataSource: [],
    };
  },

  computed: {
    ...mapState({
      user: state => state.account.user,
    })

  },

  methods: {
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    selectMchntNo(val) {
      try {
        this.$get("/admin/igas/historyMchntOrderReport/mchntBaseInfoListByNo", {
          q: encodeURIComponent(`&${this.query.instId}`)
        }).then((r) => {
          this.mchntNoList = r.data.results;
          console.log("this.mchntNoList ===", this.mchntNoList)
        });
      } catch (e) {
        console.error(e);
      }
    },
    setMchntNoValue(index) {
      this.query.mchntNo = this.mchntNoList[index].name
      console.log("this.mchntNoList[index].name====", this.mchntNoList[index].name)
    },

    selectTxnName(val) {
      try {
        this.$get("/admin/igas/mchntOrderReport/srcTxnInfoList", {
          q: encodeURIComponent(`&${this.query.instId}`)
        }).then((r) => {
          this.txnNameList = r.data.results;
          console.log("this.txnNameList ===", this.txnNameList)
        });
      } catch (e) {
        console.error(e);
      }
    },
    setTxnNameValue(index) {
      this.query.txnName = this.txnNameList[index].name
      console.log("this.txnNameList[index].name====", this.txnNameList[index].name)
    },

    selectTxnStatus(val) {
      try {
        this.$get("/admin/igas/mchntOrderReport/txnStatusList", {
          q: encodeURIComponent(`&${this.query.instId}`)
        }).then((r) => {
          this.txnStatusList = r.data.results;
          console.log("this.txnStatusList ===", this.txnStatusList)
        });
      } catch (e) {
        console.error(e);
      }
    },
    setTxnStatusValue(index) {
      this.query.txnStatus = this.txnStatusList[index].name
      console.log("this.txnStatusList[index].name====", this.txnStatusList[index].name)
    },

    selectSyy(val) {
      try {
        if (!this.query.mchntName) {
          this.$confirm({
            title: '提示',
            content: '请选择商户',
          });
        }
        this.$get("/admin/igas/historyMchntOrderReport/userInfoList", {
          q: encodeURIComponent(`&${this.query.instId}` + `&${this.syyAboutId}`)
        }).then((r) => {
          this.syyList = r.data.results;
          console.log("this.syyList ===", this.syyList)
        });
      } catch (e) {
        console.error(e);
      }
    },
    setSyyValue(index) {
      this.query.syy = this.syyList[index].name
      console.log("this.syyList[index].name====", this.syyList[index].name)
    },

    handlerChange(value, item) {
      if (item.indexOf('Time') > -1) {
        value = moment(value).format('HH:mm:ss');
      }
      this.query[item] = value

    },
    handlerSearch(item) {
    },
    industryTypeChange(value) {
      this.query.industryType = value;
    },
    industryTypeSearch(item) {
    },


    handleTableChange(pagination) {
      // 将这三个参数赋值给Vue data，用于后续使用
      this.paginationInfo = pagination
      this.fetch({
        ...this.query,
      })
    },

    onSelectChange(selectedRowKeys) {   //接收数组，存放到前面定义的数组中
      this.selectedRowKeys = selectedRowKeys
    },

    reset() {
      let iId = this.query.instId
      // 取消选中
      this.selectedRowKeys = []
      // 重置分页
      this.$refs.table.pagination.current = this.pagination.defaultCurrent
      if (this.paginationInfo) {
        this.paginationInfo.current = this.pagination.defaultCurrent
        this.paginationInfo.pageSize = this.pagination.defaultPageSize
      }
      // 重置查询参数
      this.query = {}
      this.query.instId = iId
      // // 清空时间选择
      this.form.setFieldsValue({timeForm:[]});
      this.fetch()
    },


    handleInstChange(value) {
      this.query.instId = value;
      if (value != "") {
        let params = {}
        params.instId = value;
        params.userId = this.user.id;
        this.$get('/admin/igas/historyMchntOrderReport/findByPage', {...params}).then((r) => {

          this.dataSource = r.data.rows;
          this.search();
        })
      }
    },

    fetch(params = {}) {
      params.userId = this.user.id;
      this.loading = true
      if (this.paginationInfo) {
        // 如果分页信息不为空，则设置表格当前第几页，每页条数，并设置查询分页参数
        this.$refs.table.pagination.current = this.paginationInfo.current
        this.$refs.table.pagination.pageSize = this.paginationInfo.pageSize
        params.pageSize = this.paginationInfo.pageSize
        params.pageNum = this.paginationInfo.current
      } else {
        // 如果分页信息为空，则设置为默认值
        params.pageSize = this.pagination.defaultPageSize
        params.pageNum = this.pagination.defaultCurrent
      }
      this.$get('/admin/igas/historyMchntOrderReport/findByPage', {
        ...params
      }).then((r) => {
        let data = r.data
        const pagination = {...this.pagination}
        pagination.total = data.total
        this.dataSource = data.rows
        this.pagination = pagination
        this.loading = false
      })
    },

    async search(e) {
      e && e.preventDefault && e.preventDefault();
      let params = {}
      // 初始化时间
      let timeData = this.form.getFieldsValue(['timeForm']);
      if (timeData.timeForm && timeData.timeForm.length > 0) {
        console.log(moment(timeData.timeForm[0]).format('YYYYMMDD'))
        timeData.starTime = moment(timeData.timeForm[0]).format('YYYYMMDD');
        timeData.endTime = moment(timeData.timeForm[1]).format('YYYYMMDD');
        params.startTime = timeData.starTime ;
        params.endTime = timeData.endTime
      }else {
        params.startTime = this.query.startTime
        params.endTime = this.query.endTime
      }
      params.userId = this.user.id
      params.instId = this.query.instId
      params.acqInstCode = this.query.acqInstCode
      params.mchntName = this.query.mchntName
      params.mchntNo = this.query.mchntNo
      params.txnName = this.query.txnName
      params.txnStatus = this.query.txnStatustxnStatus
      params.syy = this.query.syy
      params.frontSeqNum = this.query.frontSeqNum
      params.payerAcctInfo = this.query.payerAcctInfo
      params.orderAmtStart = this.query.orderAmtStart
      params.orderAmtEnd = this.query.orderAmtEnd
      params.mchntOrderId = this.query.mchntOrderId
      params.hisTory=true
      this.fetch({
        ...params,
      })

    },
    openModal(type = "add", beanInfo) {
      this.modalTitle = {
        add: "新增",
        edit: "编辑",
        view: "详情",
        delete: "注销",
      }[type];
      this.modalVisible = true;
      this.$nextTick(() => {
        this.$refs.modalForm.setOperatorType(type);
        if (type === "edit" || type === "view" || type === "delete") {
          this.$refs.modalForm.setBeanInfo(beanInfo);
        }
        this.$refs.modalForm.resetFields();
      });
    },
    async submit() {
      const res = await this.$refs.modalForm.submit();
      if (res) {
        this.modalVisible = false;
        this.pagination.defaultCurrent = 1;
        await this.search();
      }
    },
    async add(item) {
      this.openModal("add", item);
    },
    async edit(item) {
      this.openModal("edit", item);
    },
    view(item) {
      this.openModal("view", item);
    },

    async cancel(item) {
      try {
        const res = await this.$post('/admin/igas/pTxnCfg/changeStatus',
          {
            txnNum: item.txnNum,
            bizType: item.bizType,
            txnGroup: item.txnGroup,
            bizProdCode: item.bizProdCode,
            supportFlag: item.supportFlag === 'N' ? 'Y' : 'N'
          })
        if (res.status === 200) {
          this.$message.success('操作成功')
          this.pagination.defaultCurrent = 1
          await this.search()
        }
      } catch (e) {
        console.error(e)
      }
    },
    async forbid(item) {
      if (item.agentStatus === "03") {
        return this.$message.warning("已注销数据不允许重复注销");
      }
      this.openModal("delete", item);
    },
    exportExcel(item) {
    },
    handleClose() {
      this.open = false;
    },
  },
  mounted() {
    this.$get('admin/upmporg/getInstList').then((r) => {
      this.instIdData = r.data
    })
    if(!this.user.admin){
      this.$set(this.query,"instId",this.user.instId);
      this.search();
    }
    // this.search();
  },
    //下拉框分页名称分页
    watch: {
        'query.instId'(newValue, oldValue) {
            if (newValue !== oldValue) {
                this.listUrlParam= {'instId': newValue}

                this.$refs.mchntBaseInfoListByNameSelect.listUrlParam= {'instId': newValue}
                this.$refs.mchntBaseInfoListByNameSelect.loadDatas();

                this.$refs.acqInstCodeSelect.listUrlParam= {'instId': newValue}
                this.$refs.acqInstCodeSelect.loadDatas();
            }
        }
    }
};
</script>
<style lang="less" scoped>
@import "../../../../../static/less/Common";
</style>
